//
//  CTChatSendView.swift
//  WalkNovel
//
//  Created by Kevin on 2023/2/16.
//

import UIKit
import SnapKit

let SendHeight = 83.0

class ChatSendView: UIView {
    
    lazy var textView: IQTextView = {
        let view = IQTextView()
        view.placeholder = "请输入你想问的问题"
        view.placeholderTextColor = .init(named: "gray_999999")
        view.font = .ct_font(name: .regular, size: 14)
        view.returnKeyType = .done
        view.keyboardDismissMode = .none
        view.textColor = .init(named: "black_333333")
        view.tintColor = .lightGray
        view.backgroundColor = .init(named: "gray_EAEAEA")
        view.textContainer.lineFragmentPadding = 10
        view.automaticallyAdjustsScrollIndicatorInsets = false
        view.delegate = self
        view.ct_cornerWithBorder(4)
        return view
    }()
    
    lazy var sendBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("发送", for: .normal)
        btn.setTitleColor(.ct_colorWithHexString("2090FB", 0.5), for: .normal)
        btn.titleLabel?.font = .ct_font(name: .medium, size: 14)
        btn.rx.tap.bind { [weak self] in
            self?.sendComment()
        }.disposed(by: rx.disposeBag)
        btn.isEnabled = false
        return btn
    }()
    
    var sendClosure: StringClosure?
    
    var currentText: String = "" {
        didSet {
            let str = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
            sendBtn.setTitleColor(.ct_colorWithHexString("2090FB", str.count == 0 ? 0.5 : 1), for: .normal)
            sendBtn.isEnabled = str.count != 0
        }
    }
            
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        addSubview(sendBtn)
        addSubview(textView)
        sendBtn.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalTo(-10)
            make.width.height.equalTo(48)
        }
        textView.snp.makeConstraints { (make) in
            make.top.left.equalTo(12)
            make.right.equalTo(-67)
            make.bottom.equalTo(-12)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        ct_cornerWithBorder(0, 0, .white, 1, .ct_colorWithHexString("2B2B2C", 0.1), .init(width: 0, height: 1.5), 7.5)
        layer.masksToBounds = false
    }
}

extension CTChatSendView: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.count > CTRegex.SendMaxLen {
            let selectRange = textView.markedTextRange
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            let textContent = textView.text
            let textNum = textContent?.count
            if textNum! > CTRegex.SendMaxLen {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: CTRegex.SendMaxLen)
                let str = String(textContent![..<index!])
                textView.text = str
            }
            CTHUD.ct_show("最多评论\(CTRegex.SendMaxLen)个字")
            CTThread.ct_runInMainThread {
                self.textView.selectedTextRange = self.textView.textRange(from: self.textView.endOfDocument, to: self.textView.endOfDocument)
            }
        }
        currentText = textView.text
    }
    
    func heightForTextView(textView: UITextView, fixedWidth: CGFloat) -> CGFloat {
        let size = CGSize(width: fixedWidth, height: 14)
        let constraint = textView.sizeThatFits(size)
        return constraint.height
    }
    
    @objc func sendComment() {
        let text = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
        sendClosure?(text)
    }
}
